<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>First programs in PySide</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="PySide, Qt4, First programs, tutorial, Python, Linux, learn PySide">
<meta name="description" content="In this part of the PySide tutorial, we create our first programs.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container2">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content2">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>First programs in PySide</h1>


<p>
In this part of the PySide tutorial we will learn some basic functionality. 
</p>

<div class="big_hor">
<script type="text/javascript"><!--
google_ad_client = "ca-pub-9706709751191532";
/* big_horizontal */
google_ad_slot = "2904953388";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>


<h2>Simple example</h2>


<p>
The code example is very simplistic. It only shows a small window. Yet we can do a lot
with this window. We can resize it. Maximize it. Minimize it. This requires a lot of 
coding. Someone already coded this functionality. Because it repeats in most applications, 
there is no need to code it over again. So it has been hidden from a programmer.
PySide is a high level toolkit. If we would code in a lower level toolkit,
the following code example could easily have dozens of lines. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

# simple.py

import sys
from PySide import QtGui

app = QtGui.QApplication(sys.argv)

wid = QtGui.QWidget()
wid.resize(250, 150)
wid.setWindowTitle('Simple')
wid.show()

sys.exit(app.exec_())
</pre>

<p>
The above code shows a small window on the screen. 
</p>


<pre class="explanation">
import sys
from PySide import QtGui
</pre>

<p>
Here we provide the necessary imports. The basic GUI widgets are 
located in <code>QtGui</code> module.
</p>

<pre class="explanation">
app = QtGui.QApplication(sys.argv)
</pre>

<p>
Every PySide application must create an application object. 
The application object is located in the QtGui module. 
The <code>sys.argv</code> parameter is a list 
of arguments from the command line. 
Python scripts can be run from the shell. It is a way, 
how we can control the startup of our scripts. 
</p>

<pre class="explanation">
wid = QtGui.QWidget()
</pre>

<p>
The <code>QWidget</code> widget is the base class of all user interface objects in PySide.
We provide the default constructor for QWidget. The default constructor has no parent.
A widget with no parent is called a window. 
</p>

<pre class="explanation">
wid.resize(250, 150)
</pre>

<p>
The <code>resize()</code> method resizes the widget. 
It is 250px wide and 150px high.
</p>

<pre class="explanation">
wid.setWindowTitle('Simple')
</pre>

<p>
Here we set the title for our window. The title is shown in the titlebar.
</p>

<pre class="explanation">
wid.show()
</pre>

<p>
The <code>show()</code> method displays the widget on the screen. 
</p>

<pre class="explanation">
sys.exit(app.exec_())
</pre>

<p>
Finally, we enter the mainloop of the application. The event 
handling starts from this point. 
The mainloop receives events from the window system and 
dispatches them to the application widgets.
The mainloop ends, if we call the <code>exit()</code> 
method or the main widget is destroyed. 
The <code>sys.exit()</code> method ensures a clean exit. 
The environment will be informed, how the application ended.
</p>

<p>
You wonder why the <code>exec_()</code> method has an 
underscore? Everything has a meaning. 
This is obviously because the exec is a python keyword. 
And thus, <code>exec_()</code> was used instead.
</p>


<img src="/img/gui/pyside/simple.png" alt="Simple">
<div class="figure">Figure: Simple</div>


<h2>An application icon</h2>

<p>
The application icon is a small image, which is usually displayed
in the top left corner of the titlebar. It is also visible in the
taskbar. 
In the following example we will show, how we do it in PySide. We 
will also introduce some new methods.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows an icon
in the titlebar of the window.

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Icon')
        self.setWindowIcon(QtGui.QIcon('web.png'))        
    
        self.show()
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
The previous example was coded in a procedural style. Python programming language 
supports both procedural and object oriented programming styles. Programming in 
PySide means programming in OOP. 
</p>

<pre class="explanation">
class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
</pre>

<p>
The three most important things in object oriented programming are classes, data 
and methods. Here we create a new class called Example. The Example class inherits from 
<code>QtGui.QWidget</code> class. This means, that we must call two constructors. The first one 
for the Example class and the second one for the inherited class. The second one is
called with the <code>super()</code> method.
</p>

<pre class="explanation">
self.setGeometry(300, 300, 250, 150)
self.setWindowTitle('Icon')
self.setWindowIcon(QtGui.QIcon('web.png')) 
</pre>

<p>
All three methods have been inherited from the <code>QtGui.QWidget</code> class. The <code>setGeometry()</code> 
does two things. It locates the window on the screen and sets the size of the window. 
The first two parameters are the x and y positions of the window. The third is the width and 
the fourth is the height of the window. The last method sets the application icon. To do this, 
we have created a <code>QtGui.QIcon</code> object. The <code>QtGui.QIcon</code> 
receives the path to our icon to be displayed.
</p>

<pre class="explanation">
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
We put the startup code inside the <code>main()</code> method. This is a Python idiom. 
</p>

<img src="/img/gui/pyside/icon.png" alt="Icon">
<div class="figure">Figure: Icon</div>

<p>
An icon is visible in the top-left corner of the window. 
</p>


<h2>Showing a tooltip</h2>

<p>
We can provide a balloon help for any of our widgets. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This example shows a tooltip on 
a window and a button

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):
        
        QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
        
        self.setToolTip('This is a &lt;b&gt;QWidget&lt;/b&gt; widget')
        
        btn = QtGui.QPushButton('Button', self)
        btn.setToolTip('This is a &lt;b&gt;QPushButton&lt;/b&gt; widget')
        btn.resize(btn.sizeHint())
        btn.move(50, 50)       
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Tooltips')    
        self.show()
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
In this example, we show a tooltip for a two PySide widgets. 
</p>

<pre class="explanation">
QtGui.QToolTip.setFont(QtGui.QFont('SansSerif', 10))
</pre>

<p>
This static method sets a font used to render tooltips.
We use a 10px SansSerif font.
</p>

<pre class="explanation">
self.setToolTip('This is a &lt;b&gt;QWidget&lt;/b&gt; widget')
</pre>

<p>
To create a tooltip, we call the <code>setTooltip()</code> method. We can use rich text formatting. 
</p>

<pre class="explanation">
btn = QtGui.QPushButton('Button', self)
btn.setToolTip('This is a &lt;b&gt;QPushButton&lt;/b&gt; widget')
</pre>

<p>
We create a button widget and set a tooltip for it. 
</p>

<pre class="explanation">
btn.resize(btn.sizeHint())
btn.move(50, 50)       
</pre>

<p>
The button is being resized and moved on the window. The <code>sizeHint()</code>
method gives a recommended size for the button. 
</p>

<img src="/img/gui/pyside/tooltips.png" alt="Tooltips">
<div class="figure">Figure: Tooltips</div>


<h2>Closing a window</h2>

<p>
The obvious way how to close a window is to click on the x mark on the titlebar. 
In the next example, we will show, how we can programatically close our window.
We will briefly touch signals and slots. 
</p>

<p>
The following is the constructor of a <code>QtGui.QPushButton</code>, 
that we will use in our example. 
</p>

<pre>
class PySide.QtGui.QPushButton(text[, parent=None])
</pre>

<p>
The <b>text</b> parameter is a text that will be displayed on the 
button. The <b>parent</b> is the widget, onto which we place our button. 
In our case it will be a <code>QtGui.QWidget</code>. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This program creates a quit
button. When we press the button,
the application terminates. 

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):               
        
        qbtn = QtGui.QPushButton('Quit', self)
        qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)       
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Quit button')    
        self.show()
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()
</pre>

<p>
In this example, we create a quit button. Upon clicking on the
window, the application terminates. 
</p>

<pre class="explanation">
qbtn = QtGui.QPushButton('Quit', self)
</pre>

<p>
We create a push button. The button is an instance of the <code>QtGui.QPushButton</code>
class. The first parameter of the constructor is the label of the button.
The second parameter is the parent widget. The parent widget is the Example widget, which
is a <code>QtGui.QWidget</code> by inheritance. 
</p>

<pre class="explanation">
qbtn.clicked.connect(QtCore.QCoreApplication.instance().quit)
</pre>

<p>
The event processing system in PySide is built with the signal &amp; slot mechanism. 
If we click on the button, the signal <code>clicked</code> is emitted. The slot can be a 
Qt slot or any Python callable. The <code>QtCore.QCoreApplication</code> contains the main event
loop. It processes and dispatches all events. The <code>instance()</code> method gives
us the current instance. Note that <code>QtCore.QCoreApplication</code> is created with 
the <code>QtGui.QApplication</code>. The clicked signal is connected to the <code>quit()</code>
method, which terminates the application. The communication is done between two objects. 
The sender and the receiver.
The sender is the push button, the receiver is the application object. 
</p>

<img src="/img/gui/pyside/quitbutton.png" alt="quit button">
<div class="figure">Figure: Quit button</div>


<h2>Message Box</h2>

<p>
By default, if we click on the x button on the titlebar, 
the <code>QtGui.QWidget</code> is closed. Sometimes we want to modify 
this default behavior. For example, if we have a file opened in an editor
to which we did some changes. We show a message box to confirm the action.
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This program shows a confirmation 
message box when we click on the close
button of the application window. 

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):               
        
        self.setGeometry(300, 300, 250, 150)        
        self.setWindowTitle('Message box')    
        self.show()
        
    def closeEvent(self, event):
        
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes | 
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)

        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()        
        
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

</pre>

<p>
If we close the <code>QtGui.QWidget</code>, the <code>QCloseEvent</code> 
is generated. To modify the widget behaviour we need to reimplement 
the <code>closeEvent()</code> event handler.
</p>

<pre class="explanation">
reply = QtGui.QMessageBox.question(self, 'Message',
    "Are you sure to quit?", QtGui.QMessageBox.Yes | 
    QtGui.QMessageBox.No, QtGui.QMessageBox.No)
</pre>

<p>
We show a message box with two buttons. Yes and No. The first string appears on the titlebar. 
The second string is the message text displayed by the dialog. The third argument specifies
the combination of buttons appearing in the dialog. The last parameter is the default button.
It is the button, which has initially the keyboard focus. The return value is stored in the 
reply variable.
</p>

<pre class="explanation">
if reply == QtGui.QMessageBox.Yes:
    event.accept()
else:
    event.ignore() 
</pre>

<p>
Here we test the return value. If we click the Yes button, we accept the event which leads to 
the closure of the widget and to the termination of the application. 
Otherwise we ignore the close event. 
</p>

<img src="/img/gui/pyside/messagebox.png" alt="message box">
<div class="figure">Figure: Message box</div>



<h2>Centering window on the screen</h2>

<p>
The following script shows, how we can center a window on the desktop screen. 
</p>

<pre class="code">
#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
ZetCode PySide tutorial 

This program centers a window 
on the screen. 

author: Jan Bodnar
website: zetcode.com 
last edited: August 2011
"""

import sys
from PySide import QtGui

class Example(QtGui.QWidget):
    
    def __init__(self):
        super(Example, self).__init__()
        
        self.initUI()
        
    def initUI(self):               
        
        self.resize(250, 150)
        self.center()
        
        self.setWindowTitle('Center')    
        self.show()
        
    def center(self):
        
        qr = self.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
        
        
def main():
    
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

</pre>

<p>
Centering a window on the screen. 
</p>

<pre class="explanation">
self.center()
</pre>

<p>
The code that will center the window is placed
in the custom center() method.
</p>

<pre class="explanation">
qr = self.frameGeometry()
</pre>

<p>
We get a rectangle specifying the geometry of the main window. This includes
any window frame. 
</p>

<pre class="explanation">
cp = QtGui.QDesktopWidget().availableGeometry().center()
</pre>

<p>
We figure out the screen resolution of our monitor. And from this resolution, we 
get the center point. 
</p>

<pre class="explanation">
qr.moveCenter(cp)
</pre>

<p>
Our rectangle has already its width and height. Now we set the center of the rectangle
to the center of the screen. The rectangle's size is unchanged.
</p>


<pre class="explanation">
self.move(qr.topLeft())
</pre>

<p>
We move the top-left point of the application window to the top-left point of the
qr rectangle, thus centering the window on our screen. 
</p>


<p>
In this part of the PySide tutorial, we covered some basics.
</p>

<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified August 26, 2011  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

